<template>
  <div>
    <h3>{{dict_usage[usageId]}}报告查询</h3>
    <div class="body">
      <vxe-toolbar style="height: 100px;">
        <template #buttons>
          <el-row style="margin-bottom: 20px;text-align: center;" type="flex" :gutter="20" justify="space-between">
            <el-col :span="5">
              <el-date-picker size="small" v-model="doubleDate" type="daterange" align="left" unlink-panels style="width: 100%;"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
              </el-date-picker>
            </el-col>
            <el-col :span="5">
              <el-select  v-model="searchForm.sportId" size="small" collapse-tags @change="sportChange"
                filterable clearable placeholder="运动项目">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-select  v-model="searchForm.sportItemId" size="small" collapse-tags @change="sportItemChange"
                filterable clearable placeholder="运动小项">
                <el-option :label="item" :value="key" v-for="(item,key,index) in sportItemData" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-select  v-model="searchForm.coachId" size="small" collapse-tags @change="coachChange"
                filterable clearable placeholder="教练">
                <el-option :label="item" :value="key" v-for="(item,key,index) in coachData" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-select  v-model="searchForm.playerId" size="small" collapse-tags
                filterable clearable placeholder="运动员">
                <el-option :label="item" :value="key" v-for="(item,key,index) in playerData" :key="index">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row type="flex" :gutter="20" justify="space-between">
            <el-col :span="16">
              <el-button-group>
                <el-button type="success" :icon="!loading?'el-icon-printer':'vxe-icon--refresh roll'" size="small" :disabled="loading" @click="getPrintData">一键打印</el-button>
                <el-button type="success" size="small" @click="exportSelectEvent"> {{checkText}}  <i class="el-icon-document-checked"></i></el-button>
              </el-button-group>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="getSelectPlayers" style="margin: 0 10px;">搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="4">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
                @input="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" border max-height="800" stripe highlight-hover-row highlight-current-row resizable
        :loading="loading" :data="dataList" @sort-change="sortChange" :export-config="{}">
        <vxe-column field="checkbox" type="checkbox" width="60"></vxe-column>
        <vxe-table-column field="reportDate" title="报表时间" sortable min-width="150"></vxe-table-column>
        <vxe-table-column field="player" title="运动员" sortable></vxe-table-column>
        <vxe-table-column field="coach" title="教练员" sortable></vxe-table-column>
        <vxe-table-column field="sport" title="运动项目" sortable></vxe-table-column>
        <vxe-table-column field="sportItem" title="运动小项" sortable></vxe-table-column>
        <vxe-table-column field="important" title="重点运动员" sortable></vxe-table-column>
        <vxe-table-column field="template" title="测试项目" v-if="usageId==1||usageId==2" sortable></vxe-table-column>
        <vxe-table-column field="scenario" title="场景" v-else sortable></vxe-table-column>
        <vxe-table-column field="" title="操作" width="80">
          <template #default="{ row }">
            <el-button-group>
              <el-button @click="getPrintData(row)" type="primary" circle size="medium" icon="el-icon-view"></el-button>
            </el-button-group>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
      <vxe-modal v-model="printModal" title="预览" height="600" show-zoom resize width="800" show-footer>
        <template #default>
          <div id="myPrint">
            <div v-for="item,index in printData" :key="index">
              <totalPrintOne :printData="item" :usageId="usageId" />
            </div>
            <div style="page-break-before: always;"></div>
          </div>
        </template>
        <template #footer>
          <el-button @click="printEvent" type="primary" icon="el-icon-printer" size="mini">打印</el-button>
        </template>
      </vxe-modal>
    </div>
  </div>
</template>

<script>
  import {pcm4coach,currentRolePlayer,pcm4sport,sport_item_cache,template_allByUsageId,meta_sport_item_cache,get_player} from '@/api/dict.js'
  import {meta_data_selectPlayers,totalityData,meta_scenario} from '@/api/meta.js'
  import totalPrintOne from '@/components/print/totalPrintOne.vue'
  export default {
    components:{
      totalPrintOne,
    },
    data() {
      return {
        doubleDate: '',
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            },
          },{
            text: '最近半年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 6);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 12);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近两年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 12 * 2);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近三年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 12 * 3);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        usageId: this.$route.meta.usageId,
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        searchProps: [],
        dict_usage: this.$store.state.user.dict_usage,
        dict_coach: {},
        dict_player: {},
        dict_sport: {},
        dict_sportItem: {},
        dict_template: {},
        dict_scenario: {},
        dict_important: this.$store.state.user.dict_important,
        searchForm: {
          sportId: '',
          sportItemId: '',
          coachId: '',
          playerId: '',
        },
        checkText: '选择打印',
        sportItemData: {},
        coachData: {},
        playerData: {},
        printData: {},
        printModal: false,
        fullscreenLoading: false,
        search: false,
      }
    },
    created() {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 6);
      this.doubleDate = [start,end]
      this.init_dict().then(()=>{
        this.getSelectPlayers()
        this.$refs.XTable.hideColumn(this.$refs.XTable.getColumnByField('checkbox'))
      })
    },
    watch: {
      filterName(val) {
    	if(!val){
    	  this.page = {
    	  currentPage: 1,
    	  pageSize: 10,
    	  totalResult: 0,
    	  }
    	  this.search = false
    	  this.findList()
    	}
      }
    },
    methods: {
      printEvent() {
        const divEl = document.getElementById('myPrint')
        this.$XPrint({
          sheetName: '',
          content: divEl.innerHTML
        })
      },
      getPrintData(row) {
        this.loading = true
        let data = {}
        if(row.playerId){
          data = {
            playerIds: row.playerId,
            reportDates: row.reportDate,
            templates: row.templateId,
            usageId: this.usageId,
            scenarioId: 0,
          }
        }else{
          let checkData = this.$refs.XTable.getCheckboxRecords()
          let playerArr = []
          let reportDateArr = []
          let templateArr = []
          if(checkData.length != 0) {
            checkData.forEach(item=>{
              playerArr.push(item.playerId)
              reportDateArr.push(item.reportDate)
              templateArr.push(item.templateId)
            })
          }else{
            this.defaultDataList.forEach(item=>{
              playerArr.push(item.playerId)
              reportDateArr.push(item.reportDate)
              templateArr.push(item.templateId)
            })
          }
          data = {
            playerIds: playerArr.join(','),
            reportDates: reportDateArr.join(','),
            templates: templateArr.join(','),
            usageId: this.usageId,
            scenarioId: 0,
          }
        }
        totalityData(data).then(res=>{
          if(res.code === 200) {
            this.printData = res.data
            this.printModal = true
            this.loading = false
          }else{
            this.$message.error(res.message)
          }
        })
      },
      exportSelectEvent() {
        if(this.checkText == '选择打印'){
          this.checkText = '取消选择'
          this.$refs.XTable.showColumn(this.$refs.XTable.getColumnByField('checkbox'))
        }else{
          this.checkText = '选择打印'
          this.$refs.XTable.clearCheckboxRow()
          this.$refs.XTable.hideColumn(this.$refs.XTable.getColumnByField('checkbox'))
        }
      },
      clearTableFilter() {
        this.searchForm = {
          sportId: '',
          sportItemId: '',
          coachId: '',
          playerId: '',
        }
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 6);
        this.doubleDate = [start,end]
        this.sportItemData = this.dict_sportItem
        this.coachData = this.dict_coach
        this.playerData = this.dict_player
        this.getSelectPlayers()
      },
      sportChange (val) {
        this.searchForm.sportItemId = ''
        this.searchForm.coachId = ''
        this.searchForm.playerId = ''
        this.sportItemData = {}
        this.coachData = {}
        this.playerData = {}
        let sportId = this.searchForm.sportId || val
        if(sportId){
          meta_sport_item_cache({sportId:sportId}).then(res=>{
            this.sportItemData = res
          })
          pcm4coach({sportId:sportId}).then(res=>{
            this.coachData = res
          })
          get_player({usageId:this.usageId,sportId:sportId}).then(res=>{
            this.playerData = res
          })
        }
      },
      sportItemChange (val) {
        this.searchForm.coachId = ''
        this.searchForm.playerId = ''
        this.coachData = {}
        this.playerData = {}
        let sportItemId = this.searchForm.sportItemId || val
        let data = {}
        if(this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if(this.searchForm.sportItemId) data.sportItemId = this.searchForm.sportItemId
        if(sportItemId){
          pcm4coach(data).then(res=>{
            this.coachData = res
          })
          data.usageId = this.usageId
          get_player(data).then(res=>{
            this.playerData = res
          })
        }
      },
      coachChange (val) {
        this.searchForm.playerId = ''
        this.playerData = {}
        let coachId = this.searchForm.coachId || val
        let data = {}
        if(this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if(this.searchForm.sportItemId) data.sportItemId = this.searchForm.sportItemId
        if(this.searchForm.coachId) data.coachId = this.searchForm.coachId
        data.usageId = this.usageId
        if(coachId){
          get_player(data).then(res=>{
            this.playerData = res
          })
        }
      },
      getSelectPlayers(){
        let data = {}
        data.usageId = this.usageId
        data.scenarioId = 0
        data.type = 'search'
        if(this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if(this.searchForm.sportItemId) data.sportItemId = this.searchForm.sportItemId
        if(this.searchForm.coachId) data.coachId = this.searchForm.coachId
        if(this.searchForm.playerId) data.playerIdOne = this.searchForm.playerId
        if (this.doubleDate){
          data.startDate = this.$moment(this.doubleDate[0]).format('YYYY-MM-DD') + ' 00:00:00'
          data.endDate = this.$moment(this.doubleDate[1]).format('YYYY-MM-DD') + ' 00:00:00'
        }
        this.loading = true
        meta_data_selectPlayers(data).then(res=>{
          if(res.code === 200) {
            if(res.data.length != 0) {
              this.page = {
                currentPage: 1,
                pageSize: 10,
                totalResult: 0
              }
              this.init_data(res.data)
            }else{
              this.defaultDataList = []
            }
          }else{
            this.defaultDataList = []
            this.$message.error(res.message)
          }
        }).then(()=>{
          this.findList()
        })
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item=>{
          item.coach = this.dict_coach[item.coachId]
          item.player = this.dict_player[item.playerId]
          item.sport = this.dict_sport[item.sportId]
          item.sportItem = this.dict_sportItem[item.sportItemId]
          item.template = this.dict_template[item.templateId]
          item.important = this.dict_important[item.isImportant]
          item.scenario = this.dict_scenario[item.scenarioId]
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          pcm4coach().then(res=>{
            this.dict_coach = res
            this.coachData = res
          })
          pcm4sport().then(res=>{
            this.dict_sport = res
          })
          meta_scenario().then(res=>{
            res.data.forEach(item=>{
              this.dict_scenario[item.scenarioId] = item.name
            })
          })
          sport_item_cache().then(res=>{
            this.dict_sportItem = res
          })
          template_allByUsageId({usageId:this.usageId}).then(res=>{
            this.dict_template = res
          })
          currentRolePlayer().then(res=>{
            this.dict_player = res
            this.playerData = res
            resolve()
          })
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
          	currentPage: 1,
          	pageSize: this.dataList.length,
          	totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
     }
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.defaultDataList.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
      },
      findList() {
        setTimeout(() => {
          this.loading = false
          this.page.totalResult = this.defaultDataList.length
          this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
            .pageSize, this.page.currentPage * this.page.pageSize)
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
.body{
    padding: 10px;
    background-color: #FFFFFF;
  }
</style>
